package protomsg

import (
	fmt "fmt"

	"gitee.com/night-tc/gobige/common"
	"gitee.com/night-tc/gobige/msgdef"
)

func NewMsgRetByMsg(msg msgdef.IMsg, err error) (result *MsgRet) {
	msgid := uint16(0)
	if msg != nil {
		msgid, _ = msgdef.GetTypeMgr().GetMsgIDByName(msg.Name())
	}
	return NewMsgRet(msgid, err)
}

func NewMsgRet(msgid uint16, err error) (result *MsgRet) {
	result = &MsgRet{RetMsgID: uint32(msgid)}
	if err == nil {
		return result
	}
	switch verr := err.(type) {
	case *common.Error:
		result.RetCode = verr.ErrCode
		for _, v := range verr.Param {
			result.Params = append(result.Params, ArgToRespInfo(v))
		}
	default:
		result.RetCode = common.Err_Unknown.ErrCode
	}
	return result
}

// 参数装换
func ArgToRespInfo(val interface{}) *RespParam {
	param := &RespParam{}
	switch v := val.(type) {
	case int32:
		param.ParamValue = &RespParam_Int32Value{
			Int32Value: v,
		}
	case uint32:
		param.ParamValue = &RespParam_Uint32Value{
			Uint32Value: v,
		}
	case int64:
		param.ParamValue = &RespParam_Int64Value{
			Int64Value: v,
		}
	case int:
		param.ParamValue = &RespParam_Int64Value{
			Int64Value: int64(v),
		}
	case uint64:
		param.ParamValue = &RespParam_Uint64Value{
			Uint64Value: v,
		}
	case float32:
		param.ParamValue = &RespParam_FloatValue{
			FloatValue: v,
		}
	case float64:
		param.ParamValue = &RespParam_DoubleValue{
			DoubleValue: v,
		}
	case string:
		param.ParamValue = &RespParam_StringValue{
			StringValue: v,
		}
	default:
		param.ParamValue = &RespParam_StringValue{
			StringValue: fmt.Sprint(val),
		}
	}

	return param
}
